﻿#include"XZip.h"
#include<fstream>
//文件
//在压缩数据中写入文件信息
void XZip::writeGZipFileInfo(const size_t nSel)
{
	size_t currentSize = m_zipData.size();//当前字节大小
	m_zipData.resize(currentSize + sizeof(FileInfo));//扩容
	FileInfo info = { m_file[nSel].name.size(),m_file[nSel].fileSize };
	FileInfo* LPinfo = (FileInfo*)(&m_zipData[0] + currentSize);//定位指针
	*LPinfo = info;//写入文件信息
	writeGZipData(m_file[nSel].name.c_str(), m_file[nSel].name.size());//写入文件名字
}
//在压缩数据中写入文件数据
void XZip::writeGZipFileData(const size_t nSel)
{
	Info& info = m_file[nSel];
	//当前是指针指向的数据
	if (info.filePointer != NULL)
	{
		writeGZipData(info.filePointer, info.fileSize);
	}
	else
	{
		//打开待压缩的文件
		std::fstream read(info.filePath, std::ios::in | std::ios::binary | std::ios::ate);
		//遍历文件
		char* buff = new char[read.tellg()];//开辟一个文件大小的空间
		auto count = read.read(buff, read.tellg()).gcount();
		writeGZipData(buff, count);//写入文件数据
		delete[]buff;
		read.close();
	}
}
//读取文件信息
size_t XZip::readGZipFileInfo(const char* data, const size_t size, size_t offset)
{
	FileInfo* LPinfo = (FileInfo*)(data + offset);
	m_file[m_file_nSel].fileSize = LPinfo->fileSize;
	size_t nameSize = LPinfo->fileNameSize;//名字长度大小
	offset += sizeof(FileInfo);//调整偏移后面读取名字
	if (nameSize != 0)
	{
		std::vector<char> name;
		offset = readUnZipData(data, size, offset, nameSize, name);
		name.push_back('\0');
		m_file[m_file_nSel].name = &name[0];
	}
	return offset;
}
//从文件读取读取文件信息
size_t XZip::readGZipFileInfo(std::fstream& readFile)
{
	FileInfo info ;
	if (readFile.read((char*)&info, sizeof(FileInfo)).gcount() != sizeof(FileInfo))
	{
		return 0;
	}
	m_file[m_file_nSel].fileSize = info.fileSize;
	size_t nameSize = info.fileNameSize;//名字长度大小

	//调整偏移后面读取名字
	if (nameSize != 0)
	{
		std::vector<char> name;
		readUnZipData(readFile, nameSize, name);
		name.push_back('\0');
		m_file[m_file_nSel].name = &name[0];
	}
	return readFile.tellg();
}
//在压缩文件中写入压缩数据
void XZip::writeGZipFileData(const size_t nSel, std::fstream& writeFile)
{
	Info& info = m_file[nSel];
	//当前是指针指向的数据
	if (info.filePointer != NULL)
	{
		m_zipData.clear();//清空
		writeGZipData(info.filePointer, info.fileSize);
		writeFile.write(&m_zipData[0], m_zipData.size());//将压缩后的数据写入压缩文件
	}
	else
	{
		//打开待压缩的文件
		std::fstream read(info.filePath, std::ios::in | std::ios::binary);
		//遍历文件
		writeGZipData(writeFile, read);//写入文件数据
		read.close();
	}
}

